package com.koron.order.overhaul.notified;

import com.alibaba.fastjson.JSON;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.order.common.service.OrderExecuteService;
import com.koron.order.overhaul.bean.entity.OverhaulOrderBean;
import com.koron.order.overhaul.bean.entity.OverhaulOrderReportBean;
import com.koron.order.overhaul.mapper.OverhaulOrderMapper;
import com.koron.order.overhaul.service.OverhaulOrderReportService;
import com.koron.order.overhaul.utils.CommonUtils;
import com.koron.order.overhaul.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * @author twcao
 * @title: OverhaulOrderPrepareReport
 * @projectName GDH_EAM_V2
 * @description: 大修工单-编制大修报告
 * @date 2021/10/815:01
 */
@Slf4j
@Component
public class OverhaulOrderPrepareReport implements OverhaulOrderNotify<OverhaulOrderReportBean> {

    @Autowired
    private OverhaulOrderReportService reportService;

    @Autowired
    private OrderExecuteService executeService;

    @Override
    public boolean execute(SessionFactory factory, OverhaulOrderReportBean report) {
        log.info("大修工单-编制大修报告，report = {}", JSON.toJSONString(report));
        String orderId = report.getOverhaulId();
        Assert.hasText(orderId, "工单id不能为空");
        OverhaulOrderMapper mapper = factory.getMapper(OverhaulOrderMapper.class);
        OverhaulOrderBean order = mapper.getById(orderId);
        Assert.notNull(order, "工单不存在");
        Date factEndTime = executeService.queryMaxFactEndTimeByOrderId(factory, report.getOverhaulId());
        // 可重复设置，避免其他地方操作，设置了factEndTime的值
        order.setFactEndTime(factEndTime);
        mapper.saveOrUpdate(order);
        // 1、大修报告
        Assert.notNull(report, "编制大修报告不能为空");
        CommonUtils.update(report);
        EamUser user = ThreadLocalContext.get();
        report.setId(StringUtils.isBlank(report.getId()) ? CodeTools.getCode32() : report.getId());
        report.setCreateBy(user.getId());
        report.setCreateByName(user.getName());
        report.setCreateTime(new Date());
        reportService.deleteByOrderId(factory, report.getOverhaulId());
        reportService.saveOrUpdate(factory, report);
        return true;
    }

    @Override
    public int getOrder() {
        return 90004;
    }

    @Override
    public String getOrderId() {
        return "overhaulId";
    }

    @Override
    public String status() {
        return Constants.OverhaulStatus.PREPARE_REPORT;
    }
}
